<template>
  <div class="chat-container">
    <el-container>
      <el-header class="header">
        <h2>
          聊天室
          <span class="online-count">在线: {{ onlineCount }}</span>
        </h2>
      </el-header>

      <el-main class="message-area">
        <div v-for="(msg, index) in messages" :key="index">
          <div v-if="msg.type === 'system'" class="system-message">{{ msg.content }}</div>
          <div v-else :class="['message', msg.isMe ? 'my-message' : 'other-message']">
            <div class="message-user">{{ msg.user }}</div>
            <div class="message-content">{{ msg.content }}</div>
            <div class="message-time">{{ formatTime(msg.time) }}</div>
          </div>
        </div>
      </el-main>

      <el-footer class="input-area">
        <el-input v-model="inputMsg" @keyup.enter="sendMessage"></el-input>
        <el-button @click="sendMessage" :disabled="!inputMsg">发送</el-button>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMsg: "",
      onlineCount: 0,
      ws: null
    };
  },
  created() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      this.ws = new WebSocket("ws://localhost:8084/myWs");

      this.ws.onmessage = event => {
        const data = JSON.parse(event.data);

        // 只处理来自服务器的消息（不包括自己发送的消息）
        if (data.type === "system") {
          this.messages.push({
            type: "system",
            content: data.content,
            time: new Date()
          });
        } else if (data.type === "user") {
          // 这里只添加其他用户的消息，不包括自己发送的
          this.messages.push({
            type: "user",
            user: data.user,
            content: data.content,
            isMe: false, // 标记为其他人的消息
            time: new Date()
          });
        } else if (data.type === "count") {
          this.onlineCount = data.count;
        }
      };
    },
    sendMessage() {
      if (this.inputMsg.trim()) {
        // 1. 本地立即添加自己的消息（只在这里添加一次）
        this.messages.push({
          type: "user",
          user: "我",
          content: this.inputMsg,
          isMe: true, // 标记为自己的消息
          time: new Date()
        });

        // 2. 发送消息到服务器（服务器会广播给其他用户）
        this.ws.send(this.inputMsg);

        // 3. 清空输入框
        this.inputMsg = "";
      }
    },
    formatTime(date) {
      return date.toLocaleTimeString();
    }
  }
};
</script>

<style scoped>
/* 保留原有所有样式不变 */
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #409eff;
  color: white;
  line-height: 60px;
}

.online-count {
  font-size: 14px;
  margin-left: 15px;
  opacity: 0.8;
}

.message-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f5f5;
}

.system-message {
  color: #999;
  font-size: 12px;
  text-align: center;
  margin: 10px 0;
}

.message {
  margin-bottom: 15px;
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 5px;
  position: relative;
}

.my-message {
  background-color: #409eff;
  color: white;
  margin-left: auto;
}

.other-message {
  background-color: white;
  margin-right: auto;
}

.message-user {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  margin-top: 5px;
  opacity: 0.8;
}

.input-area {
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}
</style>
